package oa.hleast.xswl.controller.app.pay;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpRequest;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayDataDataserviceBillDownloadurlQueryRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayDataDataserviceBillDownloadurlQueryResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import oa.hleast.common.result.Result;
import oa.hleast.common.utils.JsonUtil;
import oa.hleast.common.web.exception.BizException;
import oa.hleast.xswl.pojo.dto.pay.PayOrderDto;
import oa.hleast.xswl.pojo.dto.pay.WxPayParamsDto;
import oa.hleast.xswl.pojo.dto.pay.ali.AlipayBill;
import oa.hleast.xswl.pojo.dto.pay.ali.AlipayQuery;
import oa.hleast.xswl.pojo.dto.pay.ali.AlipayRoot;
import oa.hleast.xswl.utils.DateUtil;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 00209
 * @email dz@hleast.com
 * @date 2021/04/12
 */

@RestController
@RequestMapping("/api.app/v1/pay")
@Slf4j
@AllArgsConstructor
public class PayController {


    private final AlipayClient alipayClient;

    /**
     * 测试环境
     */
//    private static final String HOST = "https://order.xiaoshan.gov.cn:8302/gateway/hz-order-center";
    private static final String HOST = "http://202.101.162.69:8301/gateway/hz-order-center";
    private static final String APP_KEY = "0dfe751fae704d7c8e7e67388ed4ba9f";
    private static final String APP_SECRET = "cbde282365d541a6b2b50cd6c83fb2d6";
    private static final String SUB_INST_ID = "20200612152315675";
    private static final String CALL_BACK_URL = "http://newf.mynatapp.cc/api.app/v1/pay/callback";
    private static final String ALIPAY_APP_ID = "2021000118630363";


    /**
     * 查询对账单下载地址接口
     * https://opendocs.alipay.com/open/028wo9
     *
     * @param billDate
     * @param billType
     * @return
     */
    @GetMapping("ali/downloadurlQuery")
    public Result downLoadurlQuery(@RequestParam String billDate, @RequestParam String billType) {

        AlipayDataDataserviceBillDownloadurlQueryRequest request = new AlipayDataDataserviceBillDownloadurlQueryRequest();

        request.setBizContent(JsonUtil.obj2String(AlipayBill.builder()
                .bill_type(billType)
                .bill_date(billDate)
                .build()));
        AlipayDataDataserviceBillDownloadurlQueryResponse response = null;
        try {
            response = alipayClient.certificateExecute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        if (ObjectUtils.isEmpty(response)) {
            throw new BizException("系统异常");
        }

        if (response.isSuccess()) {
            System.out.println("调用成功");
            return Result.success(response.getBillDownloadUrl());
        } else {
            System.out.println("调用失败");
        }

        return Result.success();
    }

    /**
     * 统一收单线下交易查询接口
     * https://opendocs.alipay.com/open/028sm6
     *
     * @param sysTradeNo
     * @return
     */
    @GetMapping("ali/query")
    public Result query(@RequestParam String sysTradeNo) {

        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        AlipayQuery alipayQuery = AlipayQuery.builder()
                .out_trade_no(sysTradeNo)
                .build();
        request.setBizContent(JsonUtil.obj2String(alipayQuery));
        AlipayTradeQueryResponse response = null;
        try {
            response = alipayClient.certificateExecute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if (response.isSuccess()) {
            String tradeNo = response.getTradeNo();
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        return Result.success();
    }

    /**
     * 手机网站支付接口2.0
     * https://opendocs.alipay.com/open/028sm5
     *
     * @param sysTradeNo
     * @return
     */
    @GetMapping("ali/payOrder")
    public Result aliPayOrder(@RequestParam String sysTradeNo) {

        AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
        request.setNotifyUrl(CALL_BACK_URL);
        request.setReturnUrl(CALL_BACK_URL);

        log.info("sysTradeNo = {}", sysTradeNo);

        AlipayRoot alipayRoot = AlipayRoot.builder()
                .out_trade_no(sysTradeNo)
                .total_amount(0.01)
                .subject("testCommodity")
                .product_code("QUICK_WAP_PAY")
                .quit_url("https://www.baidu.com")
                .build();

        request.setBizContent(JsonUtil.obj2String(alipayRoot));
        AlipayTradeWapPayResponse response = null;
        try {
            response = alipayClient.pageExecute(request);
            log.info("response = {}", response);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        if (ObjectUtils.isEmpty(response)) {
            throw new BizException("系统异常");
        }
        if (response.isSuccess()) {
            log.info("调用成功 currentTime = {}", DateUtil.getFormate(new Date(System.currentTimeMillis())));
            String body = response.getBody();
            log.info("响应参数 =  " + response.getBody());

            return Result.success(body);
        } else {
            String subMsg = response.getSubMsg();
            throw new BizException(subMsg);
        }
    }

    @CrossOrigin
    @PostMapping("ali/test/payOrder")
    public String aliPayOrder(@RequestParam String sysTradeNo, HttpServletResponse servletResponse) {

        AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
        request.setNotifyUrl(CALL_BACK_URL);
        request.setReturnUrl(CALL_BACK_URL);

        AlipayRoot alipayRoot = AlipayRoot.builder()
                .out_trade_no(sysTradeNo)
                .total_amount(0.01)
                .subject("测试商品")
                .product_code("QUICK_WAP_PAY")
                .build();

        request.setBizContent(JsonUtil.obj2String(alipayRoot));
        AlipayTradeWapPayResponse response = null;
        try {
            response = alipayClient.pageExecute(request);
            log.info("response = {}", response);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        if (ObjectUtils.isEmpty(response)) {
            throw new BizException("系统异常");
        }
        if (response.isSuccess()) {
            log.info("调用成功");
            String body = response.getBody();
            log.info("响应参数 =  " + response.getBody());
            try {
                servletResponse.setContentType("text/html;charset=UTF-8");
                servletResponse.getWriter().write(body);
                servletResponse.getWriter().flush();
                servletResponse.getWriter().close();
                return null;
            } catch (IOException e) {
                e.printStackTrace();
            }
//            return Result.success(body);
        } else {
            String subMsg = response.getSubMsg();
            throw new BizException(subMsg);

        }
        return "error";
    }


    @ApiOperation(value = "统一下单")
    @GetMapping("/payOrder")
    public Result payOrder() {
        WxPayParamsDto wxPayParamsDto = WxPayParamsDto.builder()
                .openid("ofS8y5an5XN2LWN1ZIyblRot1drY")
                .webName("")
                .webUrl("")
                .build();


        PayOrderDto payOrderDto = PayOrderDto.builder()
                .subInstId(SUB_INST_ID)
                .businessOrderId("x20211011")
                .businessOrderName("")
                .goodsName("蒙牛牛奶")
                .orderAccount(1)
                .payChannelId("1002_03")
                .callbackUrl("")
                .wxPayParams(wxPayParamsDto).build();

        // 加密签名
        Long currentTime = System.currentTimeMillis();
        String signData = "appKey=" + APP_KEY + "&appSecret=" + APP_SECRET + "&requestTime=" + currentTime;
        String sign = SecureUtil.md5(signData);
        log.info("sign = {},signSize = {}", sign, sign.length());


        Map<String, String> headerParams = new HashMap<>();
        headerParams.put("appKey", APP_KEY);
        headerParams.put("requestTime", currentTime.toString());
        headerParams.put("sign", sign);

        String url = HOST + "/api/order/unify/payOrder";
        log.info("url = {}", url);
        log.info("payOrderDto = {} ,headerParams = {}", payOrderDto, headerParams);
        String result = HttpRequest.post(url)
                .headerMap(headerParams, true)
                .body(JsonUtil.obj2String(payOrderDto))
                .timeout(20000)
                .execute().body();
        log.info("result = {}", result);

        return Result.success();
    }


}
